package com.cne.gmail.Gmail.controller;



import com.cne.gmail.Gmail.Excutor.ThreadResponse;
import com.cne.gmail.Gmail.Handle.GmailHandle;
import com.cne.gmail.Gmail.Handle.WatchHandler;
import com.cne.gmail.Gmail.Util.CacheUtil;
import com.cne.gmail.Gmail.dao.AddressListRepository;
import com.cne.gmail.Gmail.dao.MessageRepository;
import com.cne.gmail.Gmail.dao.UserMessageRepository;
import com.cne.gmail.Gmail.imp.SendEmailService;
import com.cne.gmail.Gmail.model.MailSenderInfo;
import com.cne.gmail.Gmail.model.MessageModel;
import com.cne.gmail.Gmail.model.UserModel;
import com.cne.gmail.Gmail.response.GmailServiceResponse;
import com.cne.gmail.Gmail.service.BackendService;
import com.cne.gmail.Gmail.service.GmailService;
import com.cne.gmail.Gmail.service.UserService;
import com.cne.gmail.Gmail.websocket.WsController;
import com.google.api.client.util.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.common.collect.Lists;
import io.swagger.annotations.*;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@RestController
@RequestMapping("gmail")
@Api(description ="邮箱管理接口")
public class GmailController {
    private final String USERID="me";
   // private final String URL="http://download.files.cnexps.com/";
    private static Logger logger = LoggerFactory.getLogger("GmailController");
    @Autowired
    GmailService gmailService;
    @Autowired
    BackendService backendService;

    @Autowired
    UserService userService;
    @Autowired
    WsController wsController;
    @Autowired
    UserMessageRepository userMessageRepository;
    @Autowired
    AddressListRepository repository;
    @Autowired
    MessageRepository messageRepository;
    @PostMapping("sendEmail")
    @ApiOperation(value = "发送邮件",notes = "发送邮件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(paramType = "query", name = "emailAddress", value = "邮箱地址", required = true, dataType = "String"),
    })
    public GmailServiceResponse<MessageModel> sendEmail(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) MailSenderInfo mailSenderInfo, @RequestParam String emailAddress) throws Exception {
        GmailServiceResponse response=new GmailServiceResponse();
        Object o = CacheUtil.getCache().get(emailAddress+"_token");
        if (o==null){
             SendEmailService sendEmailService=new SendEmailService();
             response = sendEmailService.send(userService, emailAddress, mailSenderInfo, USERID, gmailService, backendService);
            return response;
        }else {
            response.setMsg("当前用户授权已过期，请重新授权登陆");
            response.setCode(401);
            return response;
        }
    }

    @ApiOperation(value = "分页查询",notes = "分页查询")
    @PostMapping("pageQuery")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "label",value = "邮箱类型",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "currentPage",value = "当前页码",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "pageSize",value = "每页多少条",required = true,dataType = "String")
    })
    public GmailServiceResponse pageQuery(@RequestParam String emailAddress, @RequestParam String label,
                                          @RequestParam String currentPage, @RequestParam String pageSize) throws InterruptedException, ExecutionException {
        GmailServiceResponse response =new GmailServiceResponse();
        ThreadResponse threadResponse =  new ThreadResponse(emailAddress,Integer.valueOf(currentPage),Integer.valueOf(pageSize),label,backendService);
        FutureTask<ThreadResponse> result = new FutureTask<>(threadResponse);
        Thread thread=new Thread(result);
        ThreadGroup group = Thread.currentThread().getThreadGroup();
        ThreadGroup topGroup = group;
        // 遍历线程组树，获取根线程组
        while (group != null) {
            topGroup = group;
            group = group.getParent();
        }
        // 激活的线程数再加一倍，防止枚举时有可能刚好有动态线程生成
        int slackSize = topGroup.activeCount() * 2;
        Thread[] slackThreads = new Thread[slackSize];
        // 获取根线程组下的所有线程，返回的actualSize便是最终的线程数
        int actualSize = topGroup.enumerate(slackThreads);
        Thread[] atualThreads = new Thread[actualSize];
        // 复制slackThreads中有效的值到atualThreads
        System.arraycopy(slackThreads, 0, atualThreads, 0, actualSize);
        int count=0;
        for (Thread threadImport : atualThreads) {
            if (threadImport.getName().equals(emailAddress+label)){
                count++;
                threadImport.join();
                thread.start();
            }
        }
        if (count==0){
            thread.start();
        }
        Page<MessageModel> page= (Page<MessageModel>) result.get();
        if (page.getContent().size()==0){
            response.setData(null);
            response.setSuccess(false);
            response.setMsg("当前用户googgle邮箱无任何数据");
        }else {
            response.setData(page);
            response.setSuccess(true);
            response.setMsg("获取数据成功");
        }
        return response;

    }

    /**
     * 批量删除邮件
     * @param ids
     * @return
     * @throws GeneralSecurityException
     * @throws IOException
     */

    @ApiOperation(value = "批量删除邮件",notes = "批量删除邮件")
    @DeleteMapping(value = "batchDelete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "ids[]",value = "邮箱messageid数组",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String")
    })
    public GmailServiceResponse batchDelete(@RequestParam List <String> ids, @RequestParam String emailAddress) throws GeneralSecurityException, IOException {
        //大陆环境需要加代理
        //proxyHandler.proxy();
        UserModel user= userService.getUser(emailAddress);
        Gmail service=GmailHandle.service(user);
        GmailServiceResponse response=new GmailServiceResponse();
        try {
            gmailService.batchDelete(service,USERID,ids);
            backendService.batchDelteMessage(ids);
            response.setSuccess(true);
            response.setData(ids);
            response.setMsg("删除数据成功");
            return response;
        }catch (Exception e){
            e.printStackTrace();
            response.setSuccess(false);
            response.setMsg("删除数据失败,删除邮件id未找到");
            return response;
        }
    }
    /**
     * 根据邮箱和id获得指定数据
     * @param emailAddress
     * @param messageId
     * @return
     */
    @ApiOperation(value = "获取指定邮件信息",notes = "获取指定邮件信息")
    @GetMapping("getMessage")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "一个用户的messageId是唯一的，根据此获取邮箱信息",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String")
    })
    public GmailServiceResponse getMessage(@RequestParam String emailAddress, @RequestParam String messageId){
        GmailServiceResponse response =new GmailServiceResponse();
        MessageModel messageModel=  backendService.getMessage(messageId,emailAddress);
        if (messageModel==null){
            response.setMsg("请检查邮箱id是否正确");
            response.setSuccess(false);
            return response;
        }else {
            response.setSuccess(true);
            response.setMsg("获取数据成功");
            response.setData(messageModel);
            return response;
        }

    }
    /**
     * 根据邮箱和id更新邮件为已读状态
     * @param emailAddress
     * @param messageId
     * @return
     */
    @ApiOperation(value = "根据邮箱和id更新邮件为已读状态",notes = "根据邮箱和id更新邮件为已读状态")
    @PutMapping(value = "updateMessage")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "messageId",value = "一个用户的messageId是唯一的，根据此获取邮箱信息",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "emailAddress",value = "邮箱地址",required = true,dataType = "String")
    })
    public GmailServiceResponse updateMessage(@RequestParam String emailAddress, @RequestParam String messageId){
         GmailServiceResponse response =new GmailServiceResponse();
         backendService.Update(messageId,emailAddress);
         response.setData("更新成功");
         return response;

    }
    /**
     * 接收谷歌邮箱传递来的信息
     * @param message
     * @throws UnsupportedEncodingException
     */
    @PostMapping("message")
    @ResponseBody
   // @ApiOperation(value = "接收谷歌邮箱的推送信息",hidden = true)
    public void messge(@RequestBody String message , HttpServletRequest request) throws UnsupportedEncodingException {
        JSONObject mailmessage=JSONObject.fromObject(message);
        JSONObject messageObject= JSONObject.fromObject(mailmessage.get("message"));
        byte[] fileByteArray = Base64.decodeBase64(messageObject.get("data").toString());
        String text=new String(fileByteArray,"UTF-8");
        JSONObject data= JSONObject.fromObject(text);
        String emailAddress=data.get("emailAddress").toString();
        //根据邮箱地址查找当前有多少人授权登陆
        List<UserModel> userModels = userMessageRepository.findByUserName(emailAddress);
        HttpSession session = request.getSession();
        List userNames= Lists.newArrayList();
        for (UserModel userModel:userModels){
            if (session.getAttribute(userModel.getUserName())!=null){
                userNames.add(userModel.getUserName());
            }
        }
        WatchHandler watchHandler=new WatchHandler();
        UserModel user = userService.getUser(emailAddress);
        logger.info("data:"+data.toString());
        if (user==null){
            CacheUtil.CacheEmail(emailAddress,data.getString("historyId"));
        }else {
                watchHandler.handler(emailAddress,userService,backendService,wsController,repository,userNames);
                if (CacheUtil.getCache()!=null){
                    CacheUtil.removeEmailAdress(emailAddress);
                    CacheUtil.removeToken(emailAddress);
                }
        }

    }
    @GetMapping("test")
    public void test(@RequestParam String intnetdate,@RequestParam String id){
        MessageModel messageModel=new MessageModel();
        messageModel.setEmailAddress("zhangxuan000329");
        messageModel.setMessageId(id);
        messageModel.setUserName("zhnagxuang");
        messageModel.setFrom("rm");
        messageModel.setTo("张玄");
        messageModel.setCc("主题");
        messageModel.setSubject("主题测试");
        messageModel.setDate("2019-0306");
        messageModel.setIntnetdate(Long.valueOf(intnetdate));
        messageModel.setPlain("主题");
        messageModel.setHtml("主题");
        messageModel.setStatus(0);
        messageModel.setLabel("SENT");
        messageRepository.save(messageModel);

    }
}

